import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const service = axios.create({
  // baseURL: 'http://192.168.192.101:8010',
  // baseURL: 'http://192.168.0.101:8010',
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 20000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    store.state.user.token && (config.headers.Authorization = `Bearer ${store.state.user.token}`)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // if (response.data.state === 400) {
    //   console.dir(response.data.msg)
    // } else {
    // }
    // console.log(response)
    return response.data
  },
  error => {
    // 统一处理错误信息
    if (error.state === 401) {
      Message.error('登陆已过期，请重新登陆')
      router.push(`/login?redirect=${router.currentRoute.fullPath}`)
      store.commit('user/delToken')
    } else {
      console.log(error)
      Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
